<template>
	<el-dialog :close-on-click-modal="false" :title="mainTitleName()" v-model="visible" :width="800" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px" label-position="right" v-loading.fullscreen="loading">
			<el-row>
				<el-col :span="24">
					<el-form-item label="词串" prop="sentence">
						<el-input v-model="form.sentence" placeholder="词串"/>
					</el-form-item>
					<el-form-item label="词串翻译" prop="translate">
						<el-input v-model="form.translate" placeholder="词串翻译"/>
					</el-form-item>
					<!-- <el-form-item label="自动转音频" prop="isAuto">
						<el-radio-group v-model="form.isAuto">
							<el-radio :label="0">否</el-radio>
							<el-radio :label="1">是</el-radio>
						</el-radio-group>
					</el-form-item>
					<template v-if="form.isAuto != 1">
						<el-row>
							<el-col :span="12">
								<el-form-item label="常速版音频" prop="normalVoice">
									<el-col :span="10">
										<el-tooltip class="box-item" effect="dark" content="上传音频：格式为mp3,最大限制50M" placement="bottom-start">
											<scAudioButton :fileSelect="!form.normalVoice ? false : true" title="上传音频" :maxSize="50"
														   @success="setAttrFile($event, index2, 1)"></scAudioButton>
										</el-tooltip>
									</el-col>
									<el-col :span="14">
										<div class="flie-list" style="margin-left:10px;" v-if="form.normalVoice">
											<el-tag style="cursor: pointer;" class="mx-1"
													@click="previewAttrFileItem($event, index2, 1)"
													@close="delAttrFileItem($event, index2, 1)" closable>
												{{ getFileName(form.normalVoice) }}
											</el-tag>
										</div>
									</el-col>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="慢速版音频" prop="lowSpeedVoice">
									<el-col :span="10">
										<el-tooltip class="box-item" effect="dark" content="上传音频：格式为mp3,最大限制50M" placement="bottom-start">
											<scAudioButton :fileSelect="!form.lowSpeedVoice ? false : true" title="上传音频" :maxSize="50"
														   @success="setAttrFile($event, index2, 2)"></scAudioButton>
										</el-tooltip>
									</el-col>
									<el-col :span="14">
										<div class="flie-list" style="margin-left:10px;" v-if="form.lowSpeedVoice">
											<el-tag style="cursor: pointer;" class="mx-1"
													@click="previewAttrFileItem($event, index2, 2)"
													@close="delAttrFileItem($event, index2, 2)" closable>
												{{ getFileName(form.lowSpeedVoice) }}
											</el-tag>
										</div>
									</el-col>
								</el-form-item>
							</el-col>
						</el-row>
					</template> -->
					<el-form-item label="状态" prop="status">
                        <el-radio-group v-model="form.status">
                            <el-radio :label="1">启用</el-radio>
                            <el-radio :label="0">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>

	<scDialog v-model="play.status" :title="'查看音频'" :width="800">
        <div style="display: flex; align-items:center;justify-content: center;">
            <audio ref="audioControls" :src="play.src" controls style="width: 100%;"></audio>
        </div>
        <template #footer>
            <el-button @click="closePlay()">取 消</el-button>
        </template>
    </scDialog>

</template>

<script>
import scAudioButton from '@/components/scUpload/audio_button.vue'
export default {
	emits: ['success', 'closed'],
    components: {
        scAudioButton
    },
	data() {
		return {
			mode: "add",
			course: null,
			sentence: null,
            loading: false,
			visible: false,
			isSaveing: false,
            sentence_change: false,
			category: '',
			form: this.getDefaultRuleForm(),
			rules: {
				title: [
					{required: true, message: '请输入标题'}
				],
                difficultyRate: [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            var myreg = /^[1-5]$/;
                            if (value && !myreg.exec(value)) {
                                callback(new Error('只能输入1~5的数字'));
                            } else {
                                callback()
                            }
                        }
                    },
                ],
                answerLimit: [
                    {
                        required: false,
                        validator: (rule, value, callback) => {
                            var myreg = /^(-|[0-9])\d*$/;
                            if (value && !myreg.exec(value)) {
                                callback(new Error('只能输入整数'))
                            } else {
                                callback()
                            }
                        }
                    },
                ],
                sort: [
                    {
                        required: false,
                        validator: (rule, value, callback) => {
                            var myreg = /^(-|[0-9])\d*$/;
                            if (value && !myreg.exec(value)) {
                                callback(new Error('只能输入整数'))
                            } else {
                                callback()
                            }
                        }
                    },
                ],
                sentence: [
                    {required: true, message: '请输入词串'},
                ],
				translate: [
					{required: true, message: '请输入翻译', trigger: 'blur'},
				],
				normalVoice: [
					{required: true, message: '请上传常速版音频', trigger: 'blur'},
				],
				lowSpeedVoice: [
					{required: true, message: '请上传慢速版音频', trigger: 'blur'},
				],
			},
            play: {
                src: '',
                type: 1,
                status: false
            },
            voiceFiles: [],
            translationVoiceFiles: [],
			attrFile: {
                audios: [],
            },
			play: {
                src: '',
                type: 1,
                status: false
            },
		}
	},
	mounted() {

	},
	methods: {
		//显示
		open(mode = 'add', articleId) {
			this.form.articleId = articleId
			this.form.readType = 1
			this.visible = true;
			return this
		},
		setAttrFile(file, index, type) {
			if (type === 1) {
				this.form.normalVoice = file.path
				this.form.normalVoiceUrl = file.url
			}else if (type === 2) {
				this.form.lowSpeedVoice = file.path
				this.form.lowSpeedVoiceUrl = file.url
			}
        },
		previewAttrFileItem(e, index, type) {
			let url = ''
			if (type === 1) {
				url = this.form.normalVoiceUrl
			}else if (type === 2) {
				url = this.form.lowSpeedVoiceUrl
			}

			if (url) {
				this.canPlay(url)
			}
        },

		delAttrFileItem(e, index, type) {
			if (type === 1) {
				this.form.normalVoice = ''
				this.form.normalVoiceUrl = ''
			}else if (type === 2) {
				this.form.lowSpeedVoice = ''
				this.form.lowSpeedVoiceUrl = ''
			}
        },
		getFileName(o) {
            var pos = o.lastIndexOf("/")
            return o.substring(pos + 1);
        },
		canPlay(url) {
            this.play.status = true
            this.play.src = url
            this.$nextTick(() => {
                if (this.$refs.audioControls) {
                    this.$refs.audioControls.load()
                    this.$refs.audioControls.play()
                }
            })
        },
        closePlay() {
            this.$refs.audioControls && this.$refs.audioControls.pause()
            this.play.status = false
        },
		//表单提交方法
		async submit() {
			// if (!await this.$refs.dialogForm.validate().catch(() => { return false })) {
			// 	return false
			// }

            let _data = {}

            for (let key in this.form) {
                _data[key] = this.form[key]
            }
			// let personVoiceFile = null
			// if (this.form.isAuto != 1) {
			// 	personVoiceFile = {}
			// 	personVoiceFile.normalVoice = this.form.normalVoice
			// 	personVoiceFile.lowSpeedVoice = this.form.lowSpeedVoice
			// }
			// _data.personVoiceFile = personVoiceFile
			// if (this.form.isAuto != 1){
			// 	if (
			// 		(_data.personVoiceFile.normalVoice == undefined ||_data.personVoiceFile.normalVoice == '')
			// 		&& (_data.personVoiceFile.lowSpeedVoice == undefined ||_data.personVoiceFile.lowSpeedVoice == '' )
			// 	){
			// 		this.$notify.error("常速音频和慢速音频必须上传一个")
			// 		return
			// 	}
			// }
			try {
				this.isSaveing = true;
				if (this.form.id) {
					await this.$API.courseArticleSentence.action.put(_data)
				} else {
					await this.$API.courseArticleSentence.action.post(_data)
				}

				this.$emit('success')
				this.visible = false;
				this.$notify.success("保存成功")
			} finally {
				this.isSaveing = false;
			}
		},

		//表单注入数据
		async setData(row) {
            this.loading = true
			await this.$API.courseArticleSentence.action.get({id: row.id}).then(res => {
                this.loading = false
                let _data = res.data
                let _form = {
                    id: _data.id,
					articleId: _data.articleId,
					sentence: _data.sentence,
					translate: _data.translate,
					voiceFile: _data.voiceFile,
					// personVoiceFile: _data.personVoiceFile,
					isAuto: _data.isAuto ? _data.isAuto.value : 1,
                    status: _data.status ? _data.status.value : 1,
					// normalVoice:_data.personVoiceFile?.normalVoice?.path,
					// lowSpeedVoice:_data.personVoiceFile?.lowSpeedVoice?.path
                }
                this.form = _form
            }).finally(() => {
				this.loading = false
			})
        },
		getDefaultRuleForm() {
			return {
				id: null,
				articleId: '',
				sentence: '',
				translate: '',
				voiceFile: '',
				personVoiceFile: [],
				normalVoice: '',
				lowSpeedVoice: '',
				isAuto: 1,
				status: 1,
			}
		},
		mainTitleName() {
			let titleName = '编辑词串';
			return titleName;
		}
	}
}
</script>

<style lang="scss" scoped>

.sentence-block {
	position: relative;
	border: 1px solid #dcdfe6;
	padding: 20px 10px 20px 0;
	margin-bottom: 20px;
	background-color: #fff;
}

.selectItem {
	border: 1px solid #409EFF;
}

.statement-words {
	display: flex;
	flex-wrap: wrap;
	align-items: center;
}


.statement-word {
	display: flex;
	flex-direction: column; /* 垂直排列 */
	align-items: center; /* 居中对齐 */
	justify-content: center; /* 垂直居中对齐 */
	height: 100%; /* 可以根据需要调整 */
	font-size: 12px;
	margin-right: 10px;
	margin-bottom: 10px;
	cursor: pointer;

	.phonetic {
		height: 20px;
		line-height: 20px !important;
		color: red;
	}

	.original {
		line-height: 20px !important;
	}

	.translation {
		height: 20px;
		line-height: 20px !important;
	}
}

</style>
